package com.apollographql.apollo.internal.interceptor;

import com.apollographql.apollo.api.Response;
import com.apollographql.apollo.api.internal.ApolloLogger;
import com.apollographql.apollo.api.internal.Function;
import com.apollographql.apollo.api.internal.Optional;
import com.apollographql.apollo.api.internal.ResponseFieldMapper;
import com.apollographql.apollo.api.internal.Utils;
import com.apollographql.apollo.cache.ApolloCacheHeaders;
import com.apollographql.apollo.cache.normalized.ApolloStore;
import com.apollographql.apollo.cache.normalized.Record;
import com.apollographql.apollo.cache.normalized.internal.ResponseNormalizer;
import com.apollographql.apollo.cache.normalized.internal.Transaction;
import com.apollographql.apollo.cache.normalized.internal.WriteableStore;
import com.apollographql.apollo.exception.ApolloException;
import com.apollographql.apollo.interceptor.ApolloInterceptor;
import com.apollographql.apollo.interceptor.ApolloInterceptorChain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executor;

public final class ApolloCacheInterceptor implements ApolloInterceptor {
    final ApolloStore apolloStore;
    private final Executor dispatcher;
    volatile boolean disposed;
    final ApolloLogger logger;
    private final ResponseFieldMapper responseFieldMapper;
    private final boolean writeToCacheAsynchronously;

    public ApolloCacheInterceptor(ApolloStore apolloStore2, ResponseFieldMapper responseFieldMapper2, Executor dispatcher2, ApolloLogger logger2, boolean writeToCacheAsynchronously2) {
        this.apolloStore = (ApolloStore) Utils.checkNotNull(apolloStore2, "cache == null");
        this.responseFieldMapper = (ResponseFieldMapper) Utils.checkNotNull(responseFieldMapper2, "responseFieldMapper == null");
        this.dispatcher = (Executor) Utils.checkNotNull(dispatcher2, "dispatcher == null");
        this.logger = (ApolloLogger) Utils.checkNotNull(logger2, "logger == null");
        this.writeToCacheAsynchronously = writeToCacheAsynchronously2;
    }

    @Override // com.apollographql.apollo.interceptor.ApolloInterceptor
    public void interceptAsync(final InterceptorRequest request, final ApolloInterceptorChain chain, final Executor dispatcher2, final CallBack callBack) {
        dispatcher2.execute(new Runnable() {
            /* class com.apollographql.apollo.internal.interceptor.ApolloCacheInterceptor.AnonymousClass1 */

            public void run() {
                if (!ApolloCacheInterceptor.this.disposed) {
                    if (request.fetchFromCache) {
                        callBack.onFetch(FetchSourceType.CACHE);
                        try {
                            callBack.onResponse(ApolloCacheInterceptor.this.resolveFromCache(request));
                            callBack.onCompleted();
                        } catch (ApolloException e) {
                            callBack.onFailure(e);
                        }
                    } else {
                        ApolloCacheInterceptor.this.writeOptimisticUpdatesAndPublish(request);
                        chain.proceedAsync(request, dispatcher2, new CallBack() {
                            /* class com.apollographql.apollo.internal.interceptor.ApolloCacheInterceptor.AnonymousClass1.AnonymousClass1 */

                            @Override // com.apollographql.apollo.interceptor.ApolloInterceptor.CallBack
                            public void onResponse(InterceptorResponse networkResponse) {
                                if (!ApolloCacheInterceptor.this.disposed) {
                                    ApolloCacheInterceptor.this.cacheResponseAndPublish(request, networkResponse, ApolloCacheInterceptor.this.writeToCacheAsynchronously);
                                    callBack.onResponse(networkResponse);
                                    callBack.onCompleted();
                                }
                            }

                            @Override // com.apollographql.apollo.interceptor.ApolloInterceptor.CallBack
                            public void onFailure(ApolloException t) {
                                ApolloCacheInterceptor.this.rollbackOptimisticUpdatesAndPublish(request);
                                callBack.onFailure(t);
                            }

                            @Override // com.apollographql.apollo.interceptor.ApolloInterceptor.CallBack
                            public void onCompleted() {
                            }

                            @Override // com.apollographql.apollo.interceptor.ApolloInterceptor.CallBack
                            public void onFetch(FetchSourceType sourceType) {
                                callBack.onFetch(sourceType);
                            }
                        });
                    }
                }
            }
        });
    }

    @Override // com.apollographql.apollo.interceptor.ApolloInterceptor
    public void dispose() {
        this.disposed = true;
    }

    /* access modifiers changed from: package-private */
    public InterceptorResponse resolveFromCache(InterceptorRequest request) throws ApolloException {
//        ResponseNormalizer<Record> responseNormalizer = this.apolloStore.cacheResponseNormalizer();
//        Response cachedResponse = this.apolloStore.read(request.operation, this.responseFieldMapper, responseNormalizer, request.cacheHeaders).execute();
//        if (cachedResponse.getData() != null) {
//            this.logger.d("Cache HIT for operation %s", request.operation.name().name());
//            return new InterceptorResponse(null, cachedResponse, responseNormalizer.records());
//        }
        this.logger.d("Cache MISS for operation %s", request.operation.name().name());
        throw new ApolloException(String.format("Cache miss for operation %s", request.operation.name().name()));
    }

    /* access modifiers changed from: package-private */
    public Set<String> cacheResponse(InterceptorResponse networkResponse, final InterceptorRequest request) {
        if (networkResponse.parsedResponse.isPresent() && networkResponse.parsedResponse.get().hasErrors() && !request.cacheHeaders.hasHeader(ApolloCacheHeaders.STORE_PARTIAL_RESPONSES)) {
            return Collections.emptySet();
        }
        final Optional<List<Record>> records = networkResponse.cacheRecords.map(new Function<Collection<Record>, List<Record>>() {
            /* class com.apollographql.apollo.internal.interceptor.ApolloCacheInterceptor.AnonymousClass2 */

            public List<Record> apply(Collection<Record> records) {
                List<Record> result = new ArrayList<>(records.size());
                for (Record record : records) {
                    result.add(record.toBuilder().mutationId(request.uniqueId).build());
                }
                return result;
            }
        });
        if (!records.isPresent()) {
            return Collections.emptySet();
        }
//        try {
//            return (Set) this.apolloStore.writeTransaction(new Transaction<WriteableStore, Set<String>>() {
//                /* class com.apollographql.apollo.internal.interceptor.ApolloCacheInterceptor.AnonymousClass3 */
//
//                public Set<String> execute(WriteableStore cache) {
//                    return cache.merge((Collection) records.get(), request.cacheHeaders);
//                }
//            });
//        } catch (Exception e) {
//            this.logger.e("Failed to cache operation response", e);
//            return Collections.emptySet();
//        }
        return null;
    }

    /* access modifiers changed from: package-private */
    public void cacheResponseAndPublish(final InterceptorRequest request, final InterceptorResponse networkResponse, boolean async) {
        if (async) {
            this.dispatcher.execute(new Runnable() {
                /* class com.apollographql.apollo.internal.interceptor.ApolloCacheInterceptor.AnonymousClass4 */

                public void run() {
                    ApolloCacheInterceptor.this.cacheResponseAndPublishSynchronously(request, networkResponse);
                }
            });
        } else {
            cacheResponseAndPublishSynchronously(request, networkResponse);
        }
    }

    /* access modifiers changed from: package-private */
    public void cacheResponseAndPublishSynchronously(InterceptorRequest request, InterceptorResponse networkResponse) {
        try {
            Collection<? extends String> networkResponseCacheKeys = cacheResponse(networkResponse, request);
            Collection<? extends String> rolledBackCacheKeys = rollbackOptimisticUpdates(request);
            Set<String> changedCacheKeys = new HashSet<>();
            changedCacheKeys.addAll(rolledBackCacheKeys);
            changedCacheKeys.addAll(networkResponseCacheKeys);
            publishCacheKeys(changedCacheKeys);
        } catch (Exception rethrow) {
            rollbackOptimisticUpdatesAndPublish(request);
            throw rethrow;
        }
    }

    /* access modifiers changed from: package-private */
    public void writeOptimisticUpdatesAndPublish(final InterceptorRequest request) {
        this.dispatcher.execute(new Runnable() {
            /* class com.apollographql.apollo.internal.interceptor.ApolloCacheInterceptor.AnonymousClass5 */

            public void run() {
                try {
                    if (request.optimisticUpdates.isPresent()) {
                        ApolloCacheInterceptor.this.apolloStore.writeOptimisticUpdatesAndPublish(request.operation, request.optimisticUpdates.get(), request.uniqueId).execute();
                    }
                } catch (Exception e) {
                    ApolloCacheInterceptor.this.logger.e(e, "failed to write operation optimistic updates, for: %s", request.operation);
                }
            }
        });
    }

    /* access modifiers changed from: package-private */
    public void rollbackOptimisticUpdatesAndPublish(final InterceptorRequest request) {
        this.dispatcher.execute(new Runnable() {
            /* class com.apollographql.apollo.internal.interceptor.ApolloCacheInterceptor.AnonymousClass6 */

            public void run() {
                try {
                    ApolloCacheInterceptor.this.apolloStore.rollbackOptimisticUpdatesAndPublish(request.uniqueId).execute();
                } catch (Exception e) {
                    ApolloCacheInterceptor.this.logger.e(e, "failed to rollback operation optimistic updates, for: %s", request.operation);
                }
            }
        });
    }

    /* access modifiers changed from: package-private */
    public Set<String> rollbackOptimisticUpdates(InterceptorRequest request) {
        try {
            return this.apolloStore.rollbackOptimisticUpdates(request.uniqueId).execute();
        } catch (Exception e) {
            this.logger.e(e, "failed to rollback operation optimistic updates, for: %s", request.operation);
            return Collections.emptySet();
        }
    }

    /* access modifiers changed from: package-private */
    public void publishCacheKeys(final Set<String> cacheKeys) {
        this.dispatcher.execute(new Runnable() {
            /* class com.apollographql.apollo.internal.interceptor.ApolloCacheInterceptor.AnonymousClass7 */

            public void run() {
                try {
                    ApolloCacheInterceptor.this.apolloStore.publish(cacheKeys);
                } catch (Exception e) {
                    ApolloCacheInterceptor.this.logger.e(e, "Failed to publish cache changes", new Object[0]);
                }
            }
        });
    }
}
